package com.dfrz.problem.action.problem;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.expression.ParseException;

import com.dfrz.problem.model.Employee;
import com.dfrz.problem.model.ProblemInfo;
import com.dfrz.problem.model.User;
import com.dfrz.problem.service.EmployeeService;
import com.dfrz.problem.service.ProblemService;
import com.dfrz.problem.utils.IConstant;
import com.dfrz.problem.utils.Result;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 问题管理Action
 * 问题状态->0:解决,1:待分配,2:待测试,3:待解决
 * @author BIN
 *
 */
public class ProblemAction extends ActionSupport {

	private static final long serialVersionUID = 1L;
	private final static Logger logger = LoggerFactory.getLogger(ProblemAction.class);
	private ProblemService problemService;
	private EmployeeService employeeService;
	private ProblemInfo problem;
	private Employee employee;
	private User user;
	
	// 上传图片
	private File pic;     
    private String picContentType;  
    private InputStream inputStream; 
    
    private List<ProblemInfo> listProblem;
    private Map<Integer,String> mapEmployee;
    private String queryKey;// 问题查询关键字
    private String queryErro;// 查询错误提示
    private int problemId;
    private int begin;// 每页开始序号
    private int end;// 每页结束序号
    private int page;// 页码
    private int size;// 问题列表大小
    
    /**
     * 开发人员id
     */
    private Integer selectWork;
    /**
     * 测试人员id
     */
    private Integer selectTest;
    private String solve;

	/**
	 * 测试员新增问题
	 * @return
	 */
	public String add(){
		// 获取所在项目信息
		Result<Employee> result = employeeService.getEmployee(getUser().getEmail());
		employee = result.getResult();
		problem = new ProblemInfo();
		return SUCCESS;
	}
	
	/**
	 * 新增问题校验
	 * 问题状态:1--->待分配
	 * @return
	 */
	public String checkAddProblem(){
		Result<Employee> result = employeeService.getEmployee(getUser().getEmail());
		if(IConstant.NOT_LOGIN.equals(result.getCode())){
			return LOGIN;
		}
		
		String fileName = new Date().getTime() + ".jpg";
		problem.setImgPath(fileName);
		problemService.addProblem(result.getResult().getEmployeeId(),problem,result.getResult().getProject());
		upload(fileName);
		
		return SUCCESS;
	}
	
	/**
	 * 上传图片到服务器
	 * @return
	 */
	public void upload(String fileName){
		try {
            //服务器的路径  
            String realpath = ServletActionContext.getServletContext().getRealPath("/images");
            logger.debug("上传到服务器的地址:{}",realpath);
            //具体地址+文件名 ,使用当前时间的毫秒数作为文件名
            String path = realpath+"\\" + fileName;
            
            logger.debug("问题图片:{}",path);
            if (pic != null) {
                File savefile = new File(new File(realpath), fileName);
                if (!savefile.getParentFile().exists())
                    savefile.getParentFile().mkdirs();
                FileUtils.copyFile(pic, savefile);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e){
        	e.printStackTrace();
        }
	}
	
	/**
	 * 问题列表
	 * @return
	 */
	public String problemList(){
		Result<Employee> result = employeeService.getEmployee(getUser().getEmail());
		if(IConstant.NOT_LOGIN.equals(result.getCode())){
			return INPUT;
		}
		
		Result<List<ProblemInfo>> resultList = null;
		if("系统管理员".equals(getUser().getRole())){
			resultList = problemService.getAllProblem();
		}else{
			resultList = problemService.getListProblem(result.getResult());
		}
		if(IConstant.NOT_LOGIN.equals(resultList.getCode())){
			return INPUT;
		}
		
		listProblem = resultList.getResult();
		// 默认每页显示10条数据
		begin = 0;
		end = 9;
		page = 1;
		size = getListProblem().size();
		if(end >= size){
			end = size-1;
		}
		queryErro = "";
		
		return SUCCESS;
	}
	
	/**
	 * 问题查询
	 * @return
	 */
	public String queryProblem(){
		problemList();
		if(queryKey.trim().length() == 0 || queryKey == null){
			queryErro = "请输入问题关键字!";
			return SUCCESS;
		}else{
			// 将包含查询关键字的问题保留
			Iterator<ProblemInfo> it = listProblem.iterator();
			while(it.hasNext()){
				ProblemInfo problem = it.next();
				if(!problem.getProblemName().contains(queryKey)){
					it.remove();
				}
			}
			// 默认每页显示10条数据
			begin = 0;
			end = 9;
			page = 1;
			size = getListProblem().size();
			if(end >= size){
				end = size-1;
			}
		}
		
		if(listProblem.size() == 0){
			problemList();
			queryErro = "该问题不存在!";
		}
		
		return SUCCESS;
	}
	
	/**
	 * 查询下一页
	 * @return
	 */
	public String nextPage(){
		begin = end+1;
		end = begin+9;
		size = getListProblem().size();
		if(end >= size){
			end = size-1;
		}
		if(begin >= size){
			begin = size-1;
			end = begin;
		}
		page ++;
		if(page >= (size-1)/10+1){
			page = (size-1)/10+1;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 查询上一页
	 * @return
	 */
	public String prePage(){
		begin -= 10;
		if(begin <= 0){
			begin = 0;
		}
		end = begin + 9;
		if(end >= size){
			end = size-1;
		}
		page --;
		if(page <= 0){
			page = 1;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 跳转至指定页面
	 * @return
	 */
	public String toPage(){
		queryErro = "";
		// 超过最大页数时跳转回首页
		if(page > size/10+1){
			page = 1;
		}
		begin = (page-1)*10;
		end = begin+9;
		if(end >= size){
			end = size-1;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 问题详情
	 * @return
	 */
	public String problemDetail(){
		Result<ProblemInfo> result = problemService.getProblemOnId(problemId);
		problem = result.getResult();
		
		// 获取测试员
		Result<Employee> resultEmployee = employeeService.getEmployeeOnProblemId(problem.getProblemId(),3);
		// 获取员工列表
		Result<List<Employee>> employeeList = 
				employeeService.getListEmployee(problem.getProject().getProjectId());
		if(IConstant.PROBLEM_NOT_EXIST.equals(result.getCode()) || 
				IConstant.EMPLOYEE_NOT_EXIST.equals(resultEmployee.getCode()) ||
				IConstant.EMPLOYEE_NOT_EXIST.equals(employeeList.getCode())){
			addActionError(getText(IConstant.PROBLEM_NOT_EXIST) + 
					" Or " + getText(IConstant.EMPLOYEE_NOT_EXIST));
			return INPUT;
		}
		
		employee = resultEmployee.getResult();
		Iterator<Employee> it = employeeList.getResult().iterator();
		mapEmployee = new HashMap<Integer, String>();
		while(it.hasNext()){
			Employee employee = it.next();
			// 添加开发员
			if((problem.getProblemStatus() == 1 || problem.getProblemStatus() == 3) && employee.getRole().getRoleId() == 4){
				mapEmployee.put(employee.getEmployeeId(), employee.getEmployeeName());
			}else if(problem.getProblemStatus() == 2 && employee.getRole().getRoleId() == 3){
				// 添加测试员
				mapEmployee.put(employee.getEmployeeId(), employee.getEmployeeName());
			}
		}
		
		return SUCCESS;
	}
	
	/**
	 * 解决问题
	 * 问题状态:2--->待测试,3--->待解决
	 * @return
	 */
	public String solveProblem(){
		StringBuffer sb = new StringBuffer();
		String name = null;
		if(problem.getProblemStatus() == 3){
			// 开发员解决问题
			problem.setProblemStatus(2);
			// 获取开发员
			Result<Employee> resultEmployee = employeeService.getEmployeeOnProblemId(problem.getProblemId(),4);
			name = resultEmployee.getResult().getEmployeeName();
			
			// 改变问题状态
		}else if(problem.getProblemStatus() == 2){
			// 测试员追加问题
			problem.setProblemStatus(3);
			name = employee.getEmployeeName();
		}
		// 包装解答信息并 获取原始解答数据
		sb.append(problem.getProblemSolve()==null? "":problem.getProblemSolve());
		sb.append(name).append(":");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		sb.append(format.format(new Date())).append(":").append(solve).append("<br/>");
		problem.setProblemSolve(sb.toString());
		problemService.addProblemSolve(problem);
		
		return problemList();
	}
	
	/**
	 * 问题派发
	 * 问题状态:3--->待解决
	 * @return
	 */
	public String payoutProblem(){
		if(problem.getProblemStatus() == 1){
			problem.setProblemStatus(3);
			problemService.payoutProblem(problem,selectWork);
		}else if(problem.getProblemStatus() == 3){
			problem.setProblemStatus(2);
			problemService.payoutProblem(problem,selectTest);
		}
		
		return SUCCESS;
	}
	
	/**
	 * 关闭问题
	 * 测试通过,问题状态:0--->解决
	 * @return
	 */
	public String closeProblem(){
		problem.setProblemStatus(0);
		problemService.closeProblem(problem);
		
		return SUCCESS;
	}
	
	/**
	 * 问题统计
	 * @return
	 */
	public String statisticProblem(){
		return SUCCESS;
	}
	
	public void setProblem(ProblemInfo problem) {
		this.problem = problem;
	}
	
	public ProblemInfo getProblem() {
		return problem;
	}
	
	public User getUser(){
		SessionMap<String, Object> session = (SessionMap<String, Object>) ActionContext
				.getContext().getSession();
		user = (User) session.get("user");
		return user;
	}
	
	public File getPic() {
		return pic;
	}
	
	public void setPic(File pic) {
		this.pic = pic;
	}
	
	public String getPicContentType() {
		return picContentType;
	}
	
	public void setPicContentType(String picContentType) {
		this.picContentType = picContentType;
	}
	
	public InputStream getInputStream() {
		return inputStream;
	}
	
	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}
	
	public void setProblemService(ProblemService problemService) {
		this.problemService = problemService;
	}
	
	public void setEmployeeService(EmployeeService employeeService) {
		this.employeeService = employeeService;
	}
	
	public List<ProblemInfo> getListProblem() {
		return listProblem;
	}
	
	public int getBegin(){
		return begin;
	}
	
	public void setBegin(int begin) {
		this.begin = begin;
	}
	
	public int getEnd(){
		return end;
	}
	
	public void setEnd(int end) {
		this.end = end;
	}
	
	public int getPage() {
		return page;
	}
	
	public void setPage(int page) {
		this.page = page;
	}
	
	public void setProblemId(int problemId) {
		this.problemId = problemId;
	}
	
	public Employee getEmployee() {
		return employee;
	}
	
	public Map<Integer, String> getMapEmployee() {
		return mapEmployee;
	}
	
	public void setSelectTest(Integer selectTest) {
		this.selectTest = selectTest;
	}
	
	public void setSelectWork(Integer selectWork) {
		this.selectWork = selectWork;
	}
	
	public void setSolve(String solve) {
		this.solve = solve;
	}
	
	public void setQueryKey(String queryKey) {
		this.queryKey = queryKey;
	}
	
	public String getQueryErro() {
		return queryErro;
	}
}
